package com.at.controller;

import com.at.domain.BlogQuery;
import com.at.service.BlogService;
import com.at.service.TagService;
import com.at.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @author : code1997
 * @date :2020-09-2020/9/24 14:53
 */
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;

    @GetMapping({"/","index.html"})
    public String helloController1(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                                   BlogQuery blog, Model model){
        model.addAttribute("page", blogService.listBlog(pageable));
        model.addAttribute("types", typeService.listTypeTop(6));
        model.addAttribute("tags",tagService.listTagTop(10));
        model.addAttribute("recommedBlogs", blogService.listRecommedBlogTop(8));
        return "index";
    }

    /**
     * 根据传入的字符串，搜索所有标题或者文章内容包含指定字符串的文章
     * @param pageable ：分页对象
     * @param query ：查询参数
     * @param model ：返回的model模型
     * @return ：返回值
     */
    @PostMapping("/search")
    public String search(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable,
                         String query, Model model){
        model.addAttribute("page", blogService.listBlogByQuery(pageable, query));
        model.addAttribute("query", query);
        return "search";
    }
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
        model.addAttribute("blog", blogService.getBolgAndConvert(id));
        return "blog";
    }

    @GetMapping("/footer/newblog")
    public String newBlogs(Model model){
        model.addAttribute("newBlogs", blogService.listRecommedBlogTop(3));
        return "_fragments::newBlogList";
    }

}
